﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AppCommon.Animation;
using SyncApplication.Business;
using SyncLib.Client;
using SyncLib;
using System.Diagnostics;
using System.Configuration;
using log4net;
using AppCommon.SyncHistoryDSTableAdapters;



namespace SyncApplication
{
    public partial class FrmNotify : Form
    {
        public static FrmNotify Current { get; set; }
        NotifyAnimationHandle animation;
        public FrmNotify()
        {
            InitializeComponent();
            ShowInTaskbar = false;
            ControlBox = false;
            FormBorderStyle = FormBorderStyle.None;
            Size = new Size(0, 0);
            animation = new NotifyAnimationHandle(SyncAppNotify);
            animation.Interval = 600;
            Current = this;

            RefreshRunMode();
            NormalToolStrip();
            SyncAppNotify.Visible = true;

            ClientSyncContext.SyncDS.TaskSyncList.Clear();
            ClientSyncContext.SyncDS.AcceptChanges();
            ClientSyncContext.AddScopeToTaskList("ConfigScope");

            //  SyncDialog.Current.RefreshDatasource();
            SynchronizeHandle handle = new SynchronizeHandle();
            handle.ManualSynchronize();

        }
        // object lockObj = new object();
        public void RefreshRunMode()
        {
            //lock (lockObj)
            {
                if (ConfigurationManager.AppSettings[ClientConst.SK_RundMode] == "Automatic")
                {
                    timer1.Enabled = true;
                    timer1.Interval = 1000 * 60 * int.Parse(ConfigurationManager.AppSettings[ClientConst.SK_Interval]);
                }
                else
                {
                    timer1.Enabled = false;
                }
            }
        }

        private void SyncAppNotify_DoubleClick(object sender, EventArgs e)
        {
            if (ClientSyncContext.IsRunning)
            {
                SyncDialog.Current.Show();
            }
            else
                if (FrmClient.Current == null || FrmClient.Current.IsDisposed)
                {
                    FrmClient frm = new FrmClient();
                }

            FrmClient.Current.Show();
        }
        public delegate void NextTaskDelage(ClientSyncDS.TaskSyncListRow task);
        public void NextTask(ClientSyncDS.TaskSyncListRow task)
        {
            if (contextMenuStrip1.InvokeRequired)
            {
                this.Invoke(new NextTaskDelage(NextTask), new object[] { task });
                return;
            }

            toolStripSync.Text = "Đang thực hiện(" + task.ScopeName + ")";


        }
        public delegate void AnimationDelage(AnimationState sate);
        public void Animation(AnimationState state)
        {
            if (InvokeRequired)
            {

                this.Invoke(new AnimationDelage(Animation), new object[] { state });
                return;
            }
            if (state == AnimationState.Syncing)
            {
                animation.Animation(-1);
                SyncStateToolStrip();
            }
            else
            {
                animation.Stop();
                NormalToolStrip();
            }
        }
        private void SetSyncToolStrip(string text)
        {
            if (contextMenuStrip1.InvokeRequired)
            {
                Debug.WriteLine("SetSyncToolStrip - contextMenuStrip1.InvokeRequired");
                contextMenuStrip1.Invoke(new MethodInvoker(() => SetSyncToolStrip(text)));
                return;
            }
            toolStripSync.Text = text;
        }
        private void NormalToolStrip()
        {
            if (contextMenuStrip1.InvokeRequired)
            {
                Debug.WriteLine("NormalToolStrip - contextMenuStrip1.InvokeRequired");
                contextMenuStrip1.Invoke(new MethodInvoker(() => NormalToolStrip()));
                return;
            }
            toolStripSync.Enabled = true;
            toolStripSync.Text = "Đồng bộ";
            toolStripExit.Enabled = true;
            SetDefaultIcon();
        }
        private void SyncStateToolStrip()
        {
            if (contextMenuStrip1.InvokeRequired)
            {
                Debug.WriteLine("SyncStateToolStrip - contextMenuStrip1.InvokeRequired");
                contextMenuStrip1.Invoke(new MethodInvoker(() => SyncStateToolStrip()));
                return;
            }
            toolStripSync.Enabled = false;
            toolStripSync.Text = "Đang thực hiện";
            toolStripExit.Enabled = false;
        }
        public void SetDefaultIcon()
        {
            try
            {
                using (HistorySyncTableAdapter adapter = new HistorySyncTableAdapter())
                {
                    adapter.Connection.ConnectionString = CommonVariable.SqlConnectionString;
                    object temp = adapter.CountUnreviewByResult("-1");
                    if (temp.ToString() != "0")
                    {
                        animation.ShowError();
                        SyncAppNotify.Text = "Keeper Sync(" + temp.ToString() + " Lỗi)";
                        return;
                    }
                    temp = adapter.CountUnreviewByResult("1");
                    if (temp.ToString() != "0")
                    {
                        animation.ShowWarning();
                        SyncAppNotify.Text = "Keeper Sync(" + temp.ToString() + " Cảnh báo)";
                        return;
                    }
                    temp = adapter.SelectMaxSyncDate();
                    animation.ShowSuccess();
                    string des = "";
                    if (temp == DBNull.Value)
                    {
                        des = "Chưa đồng bộ";
                        animation.ShowWarning();
                    }
                    else
                        des = ((DateTime?)temp).Value.ToString("dd/MM/yyyy");
                    SyncAppNotify.Text = "Keeper Sync(" + des + ")";
                }

            }
            catch (Exception ex)
            {

                animation.ShowWarning();
                SyncAppNotify.Text = "Keeper Sync(Không lấy được trạng thái)";
            }
        }
        public void ShowError()
        {
            if (InvokeRequired)
            {

                this.Invoke(new MethodInvoker(ShowError));
                return;
            }
            animation.ShowError();
        }
        public void ShowSuccess()
        {
            if (InvokeRequired)
            {

                this.Invoke(new MethodInvoker(ShowSuccess));
                return;
            }
            animation.ShowSuccess();
        }
        public void ShowWarning()
        {
            if (InvokeRequired)
            {

                this.Invoke(new MethodInvoker(ShowWarning));
                return;
            }
            animation.ShowWarning();
        }

        private void FrmNotify_Load(object sender, EventArgs e)
        {
            try
            {
                string[] args = Environment.GetCommandLineArgs();



                new FrmClient();

                SyncAppNotify.ShowBalloonTip(1000, "Keeper Sync", "Ứng dụng đang chạy", ToolTipIcon.Info);
                if (!(args.Length > 1 && args[1].ToString() == "slient"))
                {
                    FrmClient.Current.Show();
                }
            }
            catch (Exception ex)
            {

            }

        }

        private void thoátToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SyncAppNotify.Visible = false;
            Application.ExitThread();
        }

        private void successToolStripMenuItem_Click(object sender, EventArgs e)
        {
            animation.ShowSuccess();
        }

        private void errorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            animation.ShowError();
        }

        private void warningToolStripMenuItem_Click(object sender, EventArgs e)
        {
            animation.ShowWarning();
        }

        private void animationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            animation.Animation(-1);
        }

        private void SyncAppNotify_MouseDoubleClick(object sender, MouseEventArgs e)
        {

        }

        private void đồngBộToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // SyncDialog.Current.Show();
            FrmClient.Current.SelectNode(ClientAdvTreeManipulation.SynchronizeNodeName);
            FrmClient.Current.Show();
            //SynchronizeHandle sync = new SynchronizeHandle();
            //sync.AutomaticSynchronize();
        }

        private void giaoDiệnChínhToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmClient.Current.SelectNode(ClientAdvTreeManipulation.ScopeRootNodeName);
            FrmClient.Current.Show();
        }

        private void FrmNotify_Shown(object sender, EventArgs e)
        {
            Hide();
        }
        static ILog Log = LogManager.GetLogger(typeof(Log4NetImplement));
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                timer1.Enabled = false;
                if (ClientSyncContext.IsRunning)
                    return;
                SyncAppNotify.ShowBalloonTip(1000, SyncAppNotify.BalloonTipTitle, "Bắt đầu đồng bộ [Automatic]", ToolTipIcon.Info);
                SynchronizeHandle handle = new SynchronizeHandle();
                handle.AutomaticSynchronize();
            }
            catch (Exception ex)
            {
                Log.Fatal("Timer1 Run Sync Automatic Exception:", ex);
            }
            finally
            {
                RefreshRunMode();
            }
        }

        private void cấuHìnhToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmClient.Current.SelectNode(ClientAdvTreeManipulation.OptionNodeName);
            FrmClient.Current.Show();
        }

        private void lịchSửToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmClient.Current.SelectNode(ClientAdvTreeManipulation.HistoryNodeName);
            FrmClient.Current.Show();
        }
    }
    public enum AnimationState
    {
        Syncing,
        Normal
    }
}
